package com.guanzi.nio.c6;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 异步IO文件类
 * @author 管子
 * @date 2025/3/3 20:20
 * @description: AioFileChannel 类
 */
public class AioFileChannel {

    public static void main(String[] args) throws IOException {
        try (AsynchronousFileChannel channel = AsynchronousFileChannel.open(Paths.get("data.txt"), StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocate(16);
            // 参数1 ：ByteBuffer
            // 参数2 ：读取的起始位置
            // 参数3 ：附件内容
            // 参数4 ：回调对象
            channel.read(buffer, 0, buffer,
                    // 主线程不能结束，否则回调方法无法执行
                    new CompletionHandler<Integer, ByteBuffer>() {
                @Override
                public void completed(Integer result, ByteBuffer attachment) {
                    System.out.println("读取到的字节数：" + result);
                    attachment.flip();
                    System.out.print(Charset.defaultCharset().decode(attachment));
                }

                @Override
                public void failed(Throwable exc, ByteBuffer attachment) {
                    System.out.println("读取失败");
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
        System.in.read();
    }

}
